package com.star.jersey.mybatisplus.base.web.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class RequestUtils {
    private RequestUtils() {
    }

    public static String getRequestWithCookie(HttpServletRequest httpRequest, String param) {
        String token = getRequest(httpRequest, param);
        if (StringUtils.isNotBlank(token)) {
            return token;
        } else if (ArrayUtils.isEmpty(httpRequest.getCookies())) {
            return null;
        } else {
            Cookie[] serverCookies = httpRequest.getCookies();
            for (Cookie cookie : serverCookies) {
                if (Objects.equals(param, cookie.getName())) {
                    return cookie.getValue();
                }
            }
            return null;
        }
    }

    private static String getRequest(HttpServletRequest httpRequest, String param) {
        String value = httpRequest.getHeader(param);
        if (StringUtils.isNotBlank(value)) {
            return value;
        } else {
            if (StringUtils.isBlank(value)) {
                value = httpRequest.getParameter(param);
            }
            return value;
        }
    }
}
